const items = document.querySelectorAll('.slider .list .list-item')
const next = document.getElementById('next')
const prev = document.getElementById('prev')
const thumbnails = document.querySelectorAll('.thumbnail .item')

const countItem = items.length
let itemActive = 0

next.addEventListener('click', function () {
  itemActive += 1
  if (itemActive >= countItem) {
    itemActive = 0
  }
  showSlider()
})

prev.addEventListener('click', function () {
  itemActive -= 1
  if (itemActive < 0) {
    itemActive = countItem - 1
  }
  showSlider()
})

// 自动轮播
let refreshInterval = setInterval(() => {
  next.click()
}, 3000)

function showSlider() {
  // 移除旧的active
  let findItemActiveOld = document.querySelector('.slider .list .list-item.active')
  let findthumbnailActiveOld = document.querySelector('.thumbnail .item.active')
  findItemActiveOld.classList.remove('active')
  findthumbnailActiveOld.classList.remove('active')

  // 给最新的添加active
  items[itemActive].classList.add('active')
  thumbnails[itemActive].classList.add('active')

  // 自动轮播
  clearInterval(refreshInterval)
  refreshInterval = setInterval(() => {
    next.click()
  }, 3000)
}

thumbnails.forEach((thumbnail, index) => {
  thumbnail.addEventListener('click', function() {
    itemActive = index
    showSlider()
  })
})
